#include "DataModel.h"
#include "Settings.h"
#include <QDebug>



DataModel::DataModel(QObject *parent) :
	QAbstractTableModel(parent)
{
	downloads = Settings::getDownloadsInfo();
	Download::setDownloadsCounter(Settings::getMaxDownloadId());
}

int DataModel::rowCount(const QModelIndex &parent) const {
	return downloads.size();
}

int DataModel::columnCount(const QModelIndex &parent) const {
	return 5;
}

QVariant DataModel::data(const QModelIndex &index, int role) const {
	if (role == Qt::DisplayRole) {
		switch (index.column()) {
		case 0:
			return downloads[index.row()]->getId();
		case 1:
			return downloads[index.row()]->getName();
		case 2:
			return downloads[index.row()]->getSavingPath();
		case 3:
			return downloads[index.row()]->getPriority();
		case 4:
			return downloads[index.row()]->getProgress();
		}
	} else if (role == Qt::TextAlignmentRole) {
		return Qt::AlignCenter;
	}
	return QVariant();
}


void DataModel::addDownload(Download *newDownload)
{
	emit layoutAboutToBeChanged();
	downloads.append(newDownload);
	emit layoutChanged();
}

void DataModel::save()
{
	foreach (Download *d, downloads) {
		if (d->isRunning()) {
			d->stop();
		}
	}
	Settings::saveMaxDownloadId(Download::getDownloadsCounter());
	Settings::saveDownloadsInfo(downloads);
}

void DataModel::update()
{
	emit dataChanged(index(0, 0), index(downloads.size() - 1, 4));
}

Download *DataModel::getDownloadToStart()
{
	Download *result = 0;
	foreach (Download *d, downloads) {
		if (!d->isStarted() &&
			(result == 0 ||
			 result->getPriority() < d->getPriority() ||
			 result->getPriority() == d->getPriority() &&
			 result->getId() > d->getId())) {
			result = d;
		}
	}
	return result;
}

bool DataModel::isDuplicateDownload(QString folder, QString file)
{
	foreach (Download *d, downloads) {
		if (d->isRunning() && d->getSavingPath() == folder && d->getName() == file) {
			return true;
		}
	}
	return false;
}

void DataModel::removeDownload(int downloadId)
{
	for (int i = 0; i < downloads.size(); i++) {
		if (downloads[i]->getId() == downloadId) {
			emit layoutAboutToBeChanged();
			if (downloads[i]->isRunning()) {
				downloads[i]->stop();
			}
			delete downloads[i];
			downloads.removeAt(i);
			emit layoutChanged();
			break;
		}
	}
}

void DataModel::stopDownload(int downloadId)
{
	qDebug() << "DataModel::stopDownload(int downloadId)";
	Download *downloadToStop = getDownload(downloadId);
	if (downloadToStop != 0) {
		downloadToStop->stop();
		update();
	}
}

Download *DataModel::getDownload(int downloadId)
{
	for (int i = 0; i < downloads.size(); i++) {
		if (downloads[i]->getId() == downloadId) {
			return downloads[i];
		}
	}

	return 0;
}
